<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="filter-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="权限名称" prop="permissionName">
          <el-input
            v-model="queryParams.permissionName"
            placeholder="请输入权限名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="权限编码" prop="permissionCode">
          <el-input
            v-model="queryParams.permissionCode"
            placeholder="请输入权限编码"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="权限类型" prop="permissionType">
          <el-select v-model="queryParams.permissionType" placeholder="请选择权限类型" clearable size="small">
            <el-option label="目录" :value="1" />
            <el-option label="菜单" :value="2" />
            <el-option label="按钮" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="small"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
    </el-row>

    <!-- 权限表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="permissionList"
        row-key="id"
        :default-expand-all="isExpandAll"
        :tree-props="{children: 'children'}"
        border
      >
        <el-table-column prop="permissionName" label="权限名称" :show-overflow-tooltip="true" width="160" />
        <el-table-column prop="permissionCode" label="权限编码" :show-overflow-tooltip="true" width="160" />
        <el-table-column prop="permissionType" label="权限类型" width="100" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.permissionType === 1" type="primary">目录</el-tag>
            <el-tag v-else-if="scope.row.permissionType === 2" type="success">菜单</el-tag>
            <el-tag v-else type="warning">按钮</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isDeleted === 0 ? 'success' : 'danger'">
              {{ scope.row.isDeleted === 0 ? '正常' : '已禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路由路径" :show-overflow-tooltip="true" />
        <el-table-column prop="component" label="组件路径" :show-overflow-tooltip="true" />
        <el-table-column prop="icon" label="图标" width="100" align="center">
          <template slot-scope="scope">
            <i :class="scope.row.icon"></i>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-plus"
              @click="handleAdd(scope.row)"
              v-if="scope.row.permissionType !== 3"
            >新增</el-button>
            <el-button
              v-if="scope.row.isDeleted === 0"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >禁用</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级权限">
          <el-tree-select
            v-model="form.parentId"
            :data="permissionOptions"
            :props="{ label: 'permissionName', value: 'id' }"
            placeholder="选择上级权限"
            clearable
          />
        </el-form-item>
        <el-form-item label="权限类型" prop="permissionType">
          <el-radio-group v-model="form.permissionType">
            <el-radio :label="1">目录</el-radio>
            <el-radio :label="2">菜单</el-radio>
            <el-radio :label="3">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限名称" prop="permissionName">
          <el-input v-model="form.permissionName" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限编码" prop="permissionCode">
          <el-input v-model="form.permissionCode" placeholder="请输入权限编码" />
        </el-form-item>
        <el-form-item label="组件" prop="component">
          <el-input v-model="form.component" placeholder="请输入组件名称" />
        </el-form-item>
        <el-form-item label="路由路径" prop="path" v-if="form.permissionType !== 3">
          <el-input v-model="form.path" placeholder="请输入路由路径" />
        </el-form-item>
        <el-form-item label="组件路径" prop="component" v-if="form.permissionType === 2">
          <el-input v-model="form.component" placeholder="请输入组件路径，如: system/user/index" />
        </el-form-item>
        <el-form-item label="图标" prop="icon" v-if="form.permissionType !== 3">
          <el-input v-model="form.icon" placeholder="请输入图标类名">
            <template slot="append">
              <i :class="form.icon"></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" controls-position="right" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'Permission',
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 权限表格树数据
      permissionList: [],
      // 权限树选项
      permissionOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否展开所有
      isExpandAll: true,
      // 查询参数
      queryParams: {
        permissionName: undefined,
        permissionCode: undefined,
        permissionType: undefined
      },
      // 表单参数
      form: {
        id: undefined,
        parentId: 0,
        permissionName: undefined,
        permissionCode: undefined,
        permissionType: 1,
        path: undefined,
        component: undefined,
        icon: undefined,
        sort: 0
      },
      // 表单校验
      rules: {
        permissionName: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' }
        ],
        permissionCode: [
          { required: true, message: '权限编码不能为空', trigger: 'blur' }
        ],
        permissionType: [
          { required: true, message: '权限类型不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询权限列表 */
    async getList() {
      this.loading = true
      try {
        const res = await request({
          url: '/api/admin/permissions',
          method: 'get',
          params: this.queryParams
        })
        if (res.code === 200) {
          this.permissionList = this.handleTree(res.data)
          this.permissionOptions = [{
            id: 0,
            permissionName: '主目录',
            children: this.permissionList
          }]
        }
      } catch (error) {
        if (error !== '登录已过期') {
          this.$message.error('获取权限列表失败')
        }
      }
      this.loading = false
    },
    /** 转换树形数据结构 */
    handleTree(data) {
      const parents = data.filter(item => item.parentId === 0)
      const children = data.filter(item => item.parentId !== 0)
      
      const translator = (parents, children) => {
        parents.forEach(parent => {
          children.forEach((child, index) => {
            if (child.parentId === parent.id) {
              const temp = JSON.parse(JSON.stringify(children))
              temp.splice(index, 1)
              translator([child], temp)
              if (parent.children) {
                parent.children.push(child)
              } else {
                parent.children = [child]
              }
            }
          })
        })
      }
      
      translator(parents, children)
      return parents
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        permissionName: undefined,
        permissionCode: undefined,
        permissionType: undefined
      }
      this.handleQuery()
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.isExpandAll = !this.isExpandAll
      this.$refs.table.toggleAllRows(this.isExpandAll)
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      if (row != null && row.id) {
        this.form.parentId = row.id
      }
      this.open = true
      this.title = '添加权限'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.form = { ...row }
      this.open = true
      this.title = '修改权限'
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            if (this.form.id) {
              await request({
                url: `/api/admin/permissions/${this.form.id}`,
                method: 'put',
                data: this.form
              })
            } else {
              await request({
                url: '/api/admin/permissions',
                method: 'post',
                data: this.form
              })
            }
            this.$message.success('操作成功')
            this.open = false
            this.getList()
          } catch (error) {
            if (error !== '登录已过期') {
              this.$message.error('操作失败')
            }
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认禁用名称为"' + row.permissionName + '"的权限?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await request({
            url: `/api/admin/permissions/${row.id}`,
            method: 'delete'
          })
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.getList()
          }
        } catch (error) {
          if (error !== '登录已过期') {
            this.$message.error('删除失败')
          }
        }
      })
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        parentId: 0,
        permissionName: undefined,
        permissionCode: undefined,
        permissionType: 1,
        path: undefined,
        component: undefined,
        icon: undefined,
        sort: 0
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.filter-card {
  margin-bottom: 10px;
}
.table-card {
  margin-bottom: 20px;
}
.mb8 {
  margin-bottom: 8px;
}
.small-padding {
  padding-left: 5px;
  padding-right: 5px;
}
.fixed-width {
  min-width: 200px;
}
</style> 